﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
using PMSGSC.BLL;
using PMSGSC.DAL;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Localization;
using PMSGSC.Common;

namespace PMSGSC.App
{
    public partial class frmStockOut : DevExpress.XtraEditors.XtraForm
    {
        public frmStockOut(List<Invoice> invoiceList, frmMain objMain)
        {
            InitializeComponent();
            employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);
            stockUnitBindingSource.DataSource = Unit_BLL.GetAll(frmMain.ship.Ship_ID);
            stockBindingSource.DataSource = Stock_BLL.GetAll(frmMain.ship.Ship_ID);
            main = objMain;
            if (invoiceList == null)
            {
                invoice = invoiceBindingSource.AddNew() as Invoice;
                invoice.InvoiceCode = "OUT" + DateTime.Now.Year + Invoice_BLL.GetOrderNumberVoucherOut();
                invoice.InvoiceDate = DateTime.Now.Date;
                invoice.TransType = "Used";
                invoice.Ship_ID = frmMain.ship.Ship_ID;
                

            }
            else
            {
                invoiceBindingSource.DataSource = invoiceList;
                invoice = invoiceBindingSource.Current as Invoice;
                ucLoadEquipment21.txtCode.Text = invoice.Equipment.CodeEquipment;
                ucLoadEquipment21.txtName.Text = invoice.Equipment.NameEquipment;
                ucLoadEquipment21.lbid.Text = invoice.Equipment_ID.ToString();

                ucLoadWorkOrder1.txtCode.Text = invoice.WorkOrder.WorkOrderNumber;
                ucLoadWorkOrder1.txtName.Text = invoice.WorkOrder.Title;
                ucLoadWorkOrder1.lbid.Text = invoice.WorkOrder_ID.ToString();
                
                invoiceDetailBindingSource.DataSource = InvoiceDetail_BLL.GetAll(invoice.Invoice_ID);
                partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetAll(int.Parse(ucLoadEquipment21.lbid.Text));

            }
        }
        private frmMain main;
        Invoice invoice;
        InvoiceDetail invoiceDetail;

        private void pnLeft_SizeChanged(object sender, EventArgs e)
        {

        }

        private void frmStockIn_SizeChanged(object sender, EventArgs e)
        {
            pnBottom.Height = this.Height - pnLeft.Height - txtGhiChu.Height - 40;
            txtGhiChu.Width = this.Width - 50;
        }
        private void PartCode_QueryPopUp(object sender, CancelEventArgs e)
        {
            if (ucLoadEquipment21.lbid.Text != "")
            {
                partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetAll(int.Parse(ucLoadEquipment21.lbid.Text));
            }
        }

        private void name_QueryPopUp(object sender, CancelEventArgs e)
        {
            if (ucLoadEquipment21.lbid.Text != "")
            {
                partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetAll(int.Parse(ucLoadEquipment21.lbid.Text));
            }
        }

        private void Stock_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((InvoiceDetail)gridView1.GetFocusedRow()).Stock = null;
            else
                ((InvoiceDetail)gridView1.GetFocusedRow()).Stock = BaseDAL.DB.Stocks.Single(n => n.Stock_ID == (int)e.NewValue);
        }
      
        private void btnSaveAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ucLoadEquipment21.lbid.Text == "")
            {
                XtraMessageBox.Show("Please choose component before insert value", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (invoiceDetail.Stock_ID == null)
            {
                XtraMessageBox.Show("Please choose Stock before insert value", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            SetValueBeforeInsert(invoice);
            invoice.Equipment_ID = int.Parse(ucLoadEquipment21.lbid.Text);
            if (ucLoadWorkOrder1.lbid.Text != "")
            {
                invoice.WorkOrder_ID = int.Parse(ucLoadWorkOrder1.lbid.Text);
            }
            if (invoice.Invoice_ID == 0)
            {
                invoice.Type = false;
                Invoice_BLL.Insert(invoice);
                invoice = Invoice_BLL.GetNewInvoice();
            }
            else
            {
                Invoice_BLL.Update(invoice);
            }
            InsertValueIntoInvoiceDetail();
            XtraMessageBox.Show("Insert Success !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void InsertValueIntoInvoiceDetail()
        {
            foreach (InvoiceDetail invoiceDetail in invoiceDetailBindingSource.Cast<InvoiceDetail>().ToList())
            {
                invoiceDetail.Invoice = BaseDAL.DB.Invoices.Single(n => n.Invoice_ID == invoice.Invoice_ID);
                InvoiceDetail_BLL.Update(invoiceDetail);

                LocationInStock newLocation = LocationInStock_BLL.isExits2(invoiceDetail.Part_ID.Value, invoiceDetail.Stock_ID.Value);
                if (null != newLocation)
                {
                    newLocation.Quantity -= invoiceDetail.Quantity.Value;
                    LocationInStock_BLL.Update(newLocation);
                }
            }
        }
        private void SetValueBeforeInsert(Invoice invoice)
        {
            if (invoiceDateDateEdit.ContainsFocus)
                invoice.InvoiceDate = invoiceDateDateEdit.DateTime.Date;
            if (transTypeComboBoxEdit.ContainsFocus)
                invoice.TransType = transTypeComboBoxEdit.Text;
            if (txtGhiChu.ContainsFocus)
                invoice.Note = txtGhiChu.Text;

        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = (GridView)sender;
            GridColumn PartCol = view.Columns["PartCode"];
            GridColumn StockCol = view.Columns["Stock_ID"];
            GridColumn QuantityCol = view.Columns["Quantity"];

            if (null == view.GetRowCellValue(e.RowHandle, PartCol))
            {
                e.Valid = false;
                view.FocusedColumn = PartCol;
                e.ErrorText = "Please enter the Part. ";
                view.SetColumnError(PartCol, "Part is not empty");
                return; 
            }
            if (null == view.GetRowCellValue(e.RowHandle, StockCol))
            {
                e.Valid = false;
                view.FocusedColumn = StockCol;
                e.ErrorText = "Please enter the Stock. ";
                view.SetColumnError(StockCol, "Stock is not empty");
                return; 
            }
            if (null != view.GetRowCellValue(e.RowHandle, QuantityCol) && invoiceDetail.Stock != null)
            {
                if (LocationInStock_BLL.TestQuantityPart(invoiceDetail.Part_ID.Value, invoiceDetail.Stock_ID.Value) < invoiceDetail.Quantity.Value)
                {
                    e.Valid = false;
                    view.FocusedColumn = QuantityCol;
                    e.ErrorText = "Please enter the Quantity. ";
                    view.SetColumnError(QuantityCol, "Quantity phai nho hon");
                }
            }
        }

        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl1.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                }
            }
        }

        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (invoice.Invoice_ID != 0)
            {
                frmProcessBar pb = new frmProcessBar();
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    LoadSkinToForm();
                    pb.ShowDialog();
                }
                ));
                thread.Start();
                frmPrintStockOut printStockIn = new frmPrintStockOut(invoice.Invoice_ID);
                printStockIn.MdiParent = main;
                printStockIn.Show();

                if (pb.InvokeRequired)
                    pb.BeginInvoke(new Action(() => pb.Close()));
            }
        }
        private static void LoadSkinToForm()
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.LookAndFeel.DefaultLookAndFeel obj = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            try
            {
                LookAndFeelSettings.Load("LookAndFeelSettings.dat");
            }
            catch
            {
                obj.LookAndFeel.SetSkinStyle("Blue");
            }
        }
        private void gridView1_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            GridColumn QuantityCol = gridView1.Columns["Quantity"];
            if (e.Column == QuantityCol)
            {
                if (e.Value != null)
                {
                    invoiceDetail.Quantity = int.Parse(e.Value.ToString());
                }
            }
            GridColumn StockCol = gridView1.Columns["Stock_ID"];
            if (e.Column == StockCol)
            {
                if (e.Value != null)
                {
                    invoiceDetail.Stock = BaseDAL.DB.Stocks.Single(n => n.Stock_ID == int.Parse(e.Value.ToString()));
                }
            }
        }

        private void gridView1_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            GridView view = (GridView)sender;
            GridColumn QuantityCol = view.Columns["Quantity"];
            view.SetFocusedRowCellValue(QuantityCol, 0);
        }

        private void InvoiceDetailBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            invoiceDetail = invoiceDetailBindingSource.Current as InvoiceDetail;
        }

        private void employee_IDGridLookUpEdit_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.NewValue == null)
                invoice.Employee = null;
            else
                invoice.Employee = BaseDAL.DB.Employees.Single(n => n.Employee_ID == (int)e.NewValue);
        }

        private void pnLeft_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            invoice = invoiceBindingSource.AddNew() as Invoice;
            invoice.InvoiceCode = "OUT" + DateTime.Now.Year + Invoice_BLL.GetOrderNumberVoucherOut();
            invoice.InvoiceDate = DateTime.Now.Date;
            invoice.TransType = "Used";
            invoice.Ship_ID = frmMain.ship.Ship_ID;
        }

        private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {

        }

        private void btnLoadPart_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmGridPart gridPart = new frmGridPart();
            gridPart.ShowDialog();

            GridView view = gridView1 as GridView;

            if (view.IsNewItemRow(view.FocusedRowHandle) && view.GetRow(view.FocusedRowHandle) == null)
            {
                view.AddNewRow();
            }
            if (gridPart.PartsInEquipment != null)
            {
                view.SetRowCellValue(view.FocusedRowHandle, colPartCode2, gridPart.PartsInEquipment.PartCode);
                view.SetRowCellValue(view.FocusedRowHandle, colPartName2, gridPart.PartsInEquipment.PartName);
                view.SetRowCellValue(view.FocusedRowHandle, colQuantity, 0);

                invoiceDetail.PartsInEquipment = gridPart.PartsInEquipment;

                invoiceDetail.PartCode = gridPart.PartsInEquipment.PartCode;
                invoiceDetail.PartName = gridPart.PartsInEquipment.PartName;
            }
        }
        private bool flag = false;
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            GridView view = gridControl1.FocusedView as GridView;
            if (e.Column.FieldName == "PartCode" && flag == false)
            {
                flag = true;
                if (e.Value != null && view.FocusedRowHandle == GridControl.NewItemRowHandle)
                {
                    PartsInEquipment part;
                    part = PartInEquipment_BLL.GetDataByNumber(view.GetRowCellDisplayText(view.FocusedRowHandle, e.Column));

                    if (part != null)
                    {
                        if (view.IsNewItemRow(view.FocusedRowHandle) && view.GetRow(view.FocusedRowHandle) == null)
                        {
                            view.AddNewRow();
                        }

                        view.SetRowCellValue(view.FocusedRowHandle, colPartCode2, part.PartCode);
                        view.SetRowCellValue(view.FocusedRowHandle, colPartName2, part.PartName);
                        view.SetRowCellValue(view.FocusedRowHandle, colQuantity, 0);

                        invoiceDetail.PartsInEquipment = part;

                        invoiceDetail.PartCode = part.PartCode;
                        invoiceDetail.PartName = part.PartName;
                    }
                    else
                    {
                        view.SetColumnError(colPartCode2, "Equipment cannot be empty");
                        view.SetRowCellValue(view.FocusedRowHandle, colPartCode2, "");
                        view.SetRowCellValue(view.FocusedRowHandle, colPartName2, "");
                        invoiceDetail.PartsInEquipment = null;
                    }
                    flag = false;
                }

            }
        }
    }
}